package com.iqiyi.pps.epg.api.server.proxy;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iqiyi.pps.epg.api.aop.annotation.SkipInterfaceLog;
import com.iqiyi.pps.epg.api.model.web.broadcast.TPlatformControl;
import com.iqiyi.pps.epg.api.server.web.broadcast.BroadcastControlWebService;
import com.iqiyi.pps.epg.api.utils.Constants;
import com.iqiyi.pps.epg.api.utils.ServiceUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by karkarrotxu on 2017/4/17.
 */
@Service
public class BroadcastProxy extends BaseProxy {
    private static Logger logger = LoggerFactory.getLogger(BroadcastProxy.class);

    @SkipInterfaceLog
    public String getBroadcastControl(long channelId) {
        if (channelId < 1) {
            return ServiceUtil.getResponseError(PARAMETER_ERROR);
        }
        try {
            BroadcastControlWebService.Iface service = getBroadcastService();
            List<TPlatformControl> tPlatformControls = service.get(channelId);
            if (tPlatformControls != null) {
                return getResponseWithJsonp(Constants.CODE_SUC, tPlatformControls, null, true);
            } else {
                return getResponseWithJsonp(Constants.CODE_FAIL, null, "获取失败");
            }
        } catch (Exception e) {
            logger.error("[getBroadcastControl]", e);
            return ServiceUtil.getResponseError(INTERFACE_ERROR);
        }
    }

    public String setBroadcastControl(long channelId, String params, String assignToPrograms) {
        if (channelId < 1 || StringUtils.isEmpty(params)) {
            return ServiceUtil.getResponseError(PARAMETER_ERROR);
        }
        try {
            JSONArray paramsArray = JSONArray.parseArray(params);
            List<TPlatformControl> tPlatformControls = new ArrayList<>();
            for (Object item : paramsArray) {
                JSONObject temp = (JSONObject) item;
                if (temp.containsKey("platform")) {
                    if (StringUtils.isEmpty(temp.getString("platform"))) {
                        return getResponseWithJsonp(Constants.CODE_ERROR_PARAM, null, "platfrom非空");
                    }
                    TPlatformControl model = new TPlatformControl();
                    model.setFatherId(channelId);
                    model.setPlatform(temp.getInteger("platform"));
                    // 暂时只可设置上下线状态、直播延时、地区黑名单
                    model.setIsDownloadAllowed(true);
                    model.setIsDrm(false);
                    model.setIsShareAllowed(true);
                    model.setIsCooperationAllowed(true);
                    model.setRejectSearch(Boolean.valueOf(temp.getString("rejectSearch")));
                    model.setRejectTop(false);
                    model.setRejectRecommend(false);
                    try {
                        model.setLiveDelayTime(temp.containsKey("liveDelayTime") ? temp.getInteger("liveDelayTime") : 0);
                    } catch (Exception e) {
                        return getResponseWithJsonp(Constants.CODE_ERROR_PARAM, null, "liveDelayTime参数错误");
                    }
                    model.setIpSegmentDelayTime(0);
                    model.setRegionRejectSearch(Boolean.valueOf(temp.getString("regionRejectSearch")));
                    model.setAvailableStatus(Boolean.valueOf(temp.getString("availableStatus")));
                    if (temp.containsKey("blacklist")) {
                        model.setBlacklist(temp.getString("blacklist"));
                    }
                    tPlatformControls.add(model);
                } else {
                    return getResponseWithJsonp(Constants.CODE_ERROR_PARAM, null, "platform不能为空");
                }
            }
            BroadcastControlWebService.Iface service = getBroadcastService();
            if (service.sets(channelId, tPlatformControls, Boolean.valueOf(assignToPrograms))) {
                writeChannelLog(channelId, 500, "", "success|" + params + "| force:" + assignToPrograms);
                return getResponseWithJsonp(Constants.CODE_SUC, null, "设置成功");
            }
            writeChannelLog(channelId, 500, "", "failure|" + params + "| force:" + assignToPrograms);
            return getResponseWithJsonp(Constants.CODE_SUC, null, "设置失败");
        } catch (Exception e) {
            logger.error("[setBroadcastControl]", e);
            writeChannelLog(channelId, 500, "", "exception|" + params + "| force:" + assignToPrograms);
            return getResponseWithJsonp(Constants.CODE_ERROR, null, INTERFACE_ERROR);
        }
    }

    public String setBroadcastControlAll(long channelId, String platforms, String params, String assignToPrograms) {
        if (channelId < 1 || StringUtils.isEmpty(platforms) || StringUtils.isEmpty(params)) {
            return getResponseWithJsonp(Constants.CODE_ERROR_PARAM, null, PARAMETER_ERROR);
        }
        try {
            JSONArray platformsArray = JSONArray.parseArray(platforms);
            if (platformsArray.size() < 1) {
                return getResponseWithJsonp(Constants.CODE_ERROR_PARAM, null, PARAMETER_ERROR);
            }
            JSONObject paramsObject = JSONObject.parseObject(params);
            List<TPlatformControl> tPlatformControls = new ArrayList<>();
            for (Object item : platformsArray) {
                TPlatformControl model = new TPlatformControl();
                model.setFatherId(channelId);
                model.setPlatform(Integer.valueOf(item.toString()));
                // 暂时只可设置上下线状态、直播延时、地区黑名单
                model.setIsDownloadAllowed(true);
                model.setIsDrm(false);
                model.setIsShareAllowed(true);
                model.setIsCooperationAllowed(true);
                model.setRejectSearch(Boolean.valueOf(paramsObject.getString("rejectSearch")));
                model.setRejectTop(false);
                model.setRejectRecommend(false);
                try {
                    model.setLiveDelayTime(paramsObject.containsKey("liveDelayTime") ? paramsObject.getInteger("liveDelayTime") : 0);
                } catch (Exception e) {
                    return getResponseWithJsonp(Constants.CODE_ERROR_PARAM, null, "liveDelayTime参数错误");
                }
                model.setIpSegmentDelayTime(0);
                model.setAvailableStatus(Boolean.valueOf(paramsObject.getString("availableStatus")));
                model.setRegionRejectSearch(Boolean.valueOf(paramsObject.getString("regionRejectSearch")));
                if (paramsObject.containsKey("blacklist")) {
                    model.setBlacklist(paramsObject.getString("blacklist"));
                }
                tPlatformControls.add(model);
            }
            BroadcastControlWebService.Iface service = getBroadcastService();
            if (service.sets(channelId, tPlatformControls, Boolean.valueOf(assignToPrograms))) {
                writeChannelLog(channelId, 500, "", "success|" + params + "| force:" + assignToPrograms);
                return getResponseWithJsonp(Constants.CODE_SUC, null, "设置成功");
            }
            writeChannelLog(channelId, 500, "", "failure|" + params + "| force:" + assignToPrograms);
            return getResponseWithJsonp(Constants.CODE_SUC, null, "设置失败");
        } catch (Exception e) {
            logger.error("[BasementApiServiceImpl][setBroadcastControlAll]", e);
            writeChannelLog(channelId, 500, "", "exception|" + params + "| force:" + assignToPrograms);
            return getResponseWithJsonp(Constants.CODE_ERROR, null, INTERFACE_ERROR);
        }
    }
}
